package com.ltu.m7011e.imagine.sudoku.server;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.ltu.m7011e.imagine.sudoku.client.SudokuService;

public class SudokuServiceImpl extends RemoteServiceServlet implements SudokuService
{
	private static final int BOX_SIZE = 3;
	private static final int BOARD_SIZE = BOX_SIZE*BOX_SIZE;
	private final int[][] cells = new int[BOARD_SIZE][BOARD_SIZE];
	private final int[][] input = new int[BOARD_SIZE][BOARD_SIZE];
	private int[][] visible;
	
	@Override
	public String getCells(String data)
	{
		String[] split = data.split(",");
		
		if(split[0].compareTo("cells") == 0)
		{
			for(int i = 0; i < BOARD_SIZE; i++)
			{
				for(int j = 0; j < BOARD_SIZE; j++)
				{
					cells[i][j] = 0;
				}
			}
			
			createGrid();
			stripGrid();
			
			String grid = "";
			for(int i = 0; i < BOARD_SIZE; i++)
			{
				for(int j = 0; j < BOARD_SIZE; j++)
				{
					grid += visible[i][j];
				}
			}
			
			return "grid," + grid;
		}
		else if(split[0].compareTo("correct") == 0)
		{
			buildGrid(split[1]);
			
			boolean correct = correctGrid();
			
			return "correct," + correct;
		}
		else
		{
			return "else," + data;
		}
	}
	
	private void createGrid()
	{
		int x = 0, value = 0, row = 0;
		
		for(int i = 0; i < BOX_SIZE; i++, x++)
		{
			for(int j = 0; j < BOX_SIZE; j++, x+=BOX_SIZE)
			{
				for(int k = 0; k < BOARD_SIZE; k++, x++)
				{
					row = BOX_SIZE*i+j;
					value = (x % BOARD_SIZE) + 1;
					
					cells[row][k] = value;
				}
			}
		}
	}
	
	private void stripGrid()
	{
		visible = cells;
		
		visible[0][0] = 0;
		/*
		visible[0][2] = 0;
		visible[1][1] = 0;
		visible[1][3] = 0;
		visible[2][6] = 0;
		*/
	}
	
	private boolean correctGrid()
	{
		// TODO - Check if col correct.
		// TODO - Check if box correct.
		
		boolean[] row;
		for(int i = 0; i < 2; i++)
		{
			row = new boolean[BOARD_SIZE];
			
			for(int j = 0; j < BOARD_SIZE; j++)
			{
				if(input[i][j] == 0)
				{
					System.out.println("Empty: " + i + " " + j);
					return false;
				}
				
				row[j] = false;
				row[input[i][j]-1] = true;
				System.out.println("Number: " + input[i][j]);
			}
			
			for(int j = 0; j < BOARD_SIZE; j++)
			{
				if(row[j] == false)
				{
					// TODO - Missing number.
					System.out.println("Missing (" + i + "): " + (j+1));
					return false;
				}
			}
		}
		
		return true;
	}
	
	private void buildGrid(String data)
	{
		char[] array = data.toCharArray();
		
		int k = 0;
		for(int i = 0; i < BOARD_SIZE; i++)
		{
			for(int j = 0; j < BOARD_SIZE; j++)
			{
				input[i][j] = array[k]-48;
				k++;
			}
		}
	}
}
